<?php

class QueryRESTController extends DooController {

	//POST
	function submit(){	
		require_once Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . 'class/shard-query.php'; 

		//init response
		$res = new response;
	
		//Check required Fields
		$missing = false;	
		if(!isset($_POST["sql"]) || strlen($_POST["sql"]) == 0)
			$missing = true;
		
		if($missing){
			$res->success = false;
			$res->message = "missing required field!";
			$this->setContentType("json");
			echo $res->to_json();
			exit;
		}
		
		//get vars
		$sql = $_POST["sql"];
		$schema_id = $this->params['schema_id'];
		$schema = Doo::db()->getOne('Schemata', array('where' => 'id = ' . $schema_id));		

		//init
		$shard_query = new ShardQuery($schema->schema_name);
		$shard_query->verbose = false;
				
		//execute query
		$stmt = $shard_query->query($sql);

		//check results
		if(!$stmt || $shard_query->error) {
			//return
			$res->data = $shard_query->error;
			$res->success = false;
			echo $res->to_json();
			return;
		}
		
		//build data
		$res->data = $this->json_format($shard_query, $stmt);
	
		//return
		$res->success = true;
		echo $res->to_json();
	}
 
	private function json_format($shard_query, $stmt){
		$data = array();
		//loop rows
		while($row = $shard_query->DAL->my_fetch_assoc($stmt)) {
			$data[] = $row;
		}
		return $data;
	}

}
?>
